package service

import (
	"awesomeProject/app/model"
	"awesomeProject/app/request"
	"awesomeProject/app/response"
	"awesomeProject/global"
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type InboundPlanSrv struct{}

func (i *InboundPlanSrv) Pagination(req request.InboundPlanPagination, shopIds []uint, operator model.User) response.Resp {
	offset := (req.PageIndex - 1) * req.PageSize
	filter := bson.D{}
	if req.ShopId != 0 {
		filter = append(filter, bson.E{Key: "shopId", Value: req.ShopId})
	} else {
		if req.CompanyId != 0 && operator.SuperAdmin {
			var accounts []model.Account
			err := global.Gorm.Where("company_id=? and status=1", req.CompanyId).Find(&accounts).Error
			if err != nil {
				return response.ErrQuery
			}
			shopIds = []uint{}
			for _, account := range accounts {
				shopIds = append(shopIds, account.ShopId)
			}
		}
		if len(shopIds) > 0 {
			filter = append(filter, bson.E{Key: "shopId", Value: bson.M{"$in": shopIds}})
		}
	}
	if req.PlanStatus != 0 {
		filter = append(filter, bson.E{Key: "planStatus", Value: req.PlanStatus})
	}
	if req.FulfillmentCenterId != "" {
		filter = append(filter, bson.E{Key: "fulfillmentCenterId", Value: req.FulfillmentCenterId})
	}
	if req.PlanId != "" {
		filter = append(filter, bson.E{Key: "planId", Value: req.PlanId})
	}

	match := bson.D{{
		"$match", filter,
	}}
	sort := bson.D{{"$sort", bson.M{"createdAt": -1}}}
	skip := bson.D{{"$skip", offset}}
	limit := bson.D{{"$limit", req.PageSize}}
	cursor, err := global.MongoDB.Collection("inbound_plan").Aggregate(context.TODO(), mongo.Pipeline{match, sort, limit, skip})
	if err != nil {
		return response.ErrQuery.SetMsg(err.Error())
	}
	var plans []model.InboundPlan
	if err = cursor.All(context.TODO(), &plans); err != nil {
		return response.ErrQuery
	}
	if len(plans) == 0 {
		return response.OK.WithData(map[string]interface{}{
			"total": 0,
			"list":  plans,
		})
	}
	count := bson.D{{"$count", "total"}}
	countCursor, err := global.MongoDB.Collection("inbound_plan").Aggregate(context.TODO(), mongo.Pipeline{match, count})
	if err != nil {
		return response.ErrQuery.SetMsg(err.Error())
	}
	var countResult []map[string]interface{}
	if err = countCursor.All(context.TODO(), &countResult); err != nil {
		return response.ErrQuery.SetMsg(err.Error())
	}

	return response.OK.WithData(map[string]interface{}{
		"total": countResult[0]["total"],
		"list":  plans,
	})
}
